
from kbarutils.support import support
from mt5utils.trade_utils import trade_utils
from utils.encoder_utils import EncoderUtils
from utils.list_util import getExtremun, getFrameValue, getListArrToStr, series2List
from mt5utils.mql5_utils import mql5_utils
from serverapi.product import product
from utils.getui_utils import getui_utils
from utils.logger import Logger
from utils.time_util import fmt_d, YYYYMMDDHHMMSS
from flask import Flask, request
import json
from utils.time_util import current_time

app = Flask(__name__)
mqlUtils = mql5_utils()
tradeUtils=trade_utils()

getui = getui_utils()
kSupport=support()
currentSupper = {}
loger = Logger()

mTimeLenth = 1200  # 1200==20分钟
global lastTime
lastTime=0

class webApi:
    def startServer(self):
        """
        启动Flask
        """
        app.debug = True  # 设置调试模式，生产模式的时候要关掉debug
        app.run(host="0.0.0.0", port=80)
        #app.run(port=80)


    @app.route('/extremum', methods=['GET'])
    def extremum():
        """
        极值
        """
        if mqlUtils.login():
            mDict = request.args.to_dict()
            mSymbol = mDict['symbol']
            kFrameArr = mqlUtils.getBars(mSymbol,morethan=True)
            listValue=series2List(getFrameValue(kFrameArr,"close"))
            headExtremun=getExtremun(listValue)
            supportStr=getListArrToStr(kFrameArr)
        webApi().extremuNotice(headExtremun,supportStr)
        jsonMap=json.dumps(headExtremun,ensure_ascii=False, cls=EncoderUtils)
        return str(jsonMap)+"|"+supportStr
    
    def extremuNotice(self,extremunMap,supportStr):
        '''
        极值状态提醒
        '''
        max5=int(str(extremunMap["5"]["max"]).split(",")[0])
        min5=int(str(extremunMap["5"]["min"]).split(",")[0])

        max15=int(str(extremunMap["15"]["max"]).split(",")[0])
        min15=int(str(extremunMap["15"]["min"]).split(",")[0])

        max30=int(str(extremunMap["30"]["max"]).split(",")[0])
        min30=int(str(extremunMap["30"]["min"]).split(",")[0])

        max60=int(str(extremunMap["60"]["max"]).split(",")[0])
        min60=int(str(extremunMap["60"]["min"]).split(",")[0])

        maxh4=int(str(extremunMap["4h"]["max"]).split(",")[0])
        minh4=int(str(extremunMap["4h"]["min"]).split(",")[0])

        global lastTime
        if current_time() - lastTime >= mTimeLenth:
            if max5<min5 and max15<min15 and max30<min30:
                self.printLog(extremunMap,supportStr)
                getui.pushMsg(title="交易预警", body="下跌趋势", voice="third.wav")
        
            if max5>min5 and max15>min15 and max30>min30:
                self.printLog(extremunMap,supportStr)
                getui.pushMsg(title="交易预警", body="上涨趋势", voice="third.wav")
            lastTime = current_time()
    
    def printLog(self,extremun,support):
        '''
        日志信息打印
        '''
        loger.info("\n\n\n")
        for i in extremun:
            logInfo=i+":"+json.dumps(extremun[i],ensure_ascii=False, cls=EncoderUtils)
            loger.info(logInfo)
            
        for child in support.split(";"):
            loger.info(child)

    @app.route('/getPrice', methods=['GET'])
    def getPrice():
        '''
        移动客户端调用
        '''

        mDict = request.args.to_dict()
        mSymbol = mDict['symbol']

        dictValue = None
        if mqlUtils.login():
            mInfo = mqlUtils.getCurrentInfo(mSymbol)
            kbarArr = mqlUtils.getBars(mSymbol, mInfo.bid)

            mResonate=mqlUtils.resonate(kbarArr)
            mContinuity = mqlUtils.continuity(kbarArr)
            mBollinger, bollingerCenterArr = mqlUtils.bollingerStatus(
            kbarArr, mInfo.bid)
            dictValue = {
                "Ask": str(mInfo.ask),
                "Bid": str(mInfo.bid),
                "Open": str(mInfo.session_open),
                "High": str(mInfo.bidhigh),
                "Resonate": str(mResonate),
                "Continuity": str(mContinuity),
                "Bollinger": str(mBollinger),
                "Notice": "",
                "Deviate": "",
                "KStatus": "",
                "Support": "",
            }

        if dictValue is not None:
            return json.dumps(dictValue, ensure_ascii=False)
        else:
            return json.dumps({"msg": "暂无数据"}, ensure_ascii=False)


if __name__ == '__main__':
    webApi().startServer()